#!/usr/bin/env python

"""
Creates various files and directories needed in order to build the case,
create namelists and run the case.

Any changes to env_mach_pes.xml and env_mach_specific.xml must be made
before running this.

This must be run before running case.build.

To run this initially for the case, simply run:
   ./case.setup

To rerun after making changes to env_mach_pes.xml or env_mach_specific.xml, run:
   ./case.setup --reset
"""

from standard_script_setup import *
from CIME.case       import Case

###############################################################################
def parse_command_line(args, description):
###############################################################################
    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawTextHelpFormatter)

    CIME.utils.setup_standard_logging_options(parser)

    parser.add_argument("caseroot", nargs="?", default=os.getcwd(),
                        help="Case directory to setup.\n"
                        "Default is current directory.")

    parser.add_argument("-c", "--clean", action="store_true",
                        help="Removes the batch run script for target machine.\n"
                        "If the testmode argument is present then keep the test\n"
                        "script if it is present - otherwise remove it.\n"
                        "The user_nl_xxx and Macros files are never removed by case.setup -\n"
                        "you must remove them manually.")

    parser.add_argument("-t", "--test-mode", action="store_true",
                        help="Keeps the test script when the --clean argument is used.")

    parser.add_argument("-r", "--reset", action="store_true",
                        help="Does a clean followed by setup.\n"
                        "This flag should be used when rerunning case.setup after it\n"
                        "has already been run for this case.")

    parser.add_argument("-k", "--keep", action="append", default=[],
                        help="When cleaning/resetting a case, do not remove/refresh files in this list. "
                        "Choices are batch script, env_mach_specific.xml, Macros.make, Macros.cmake. "
                        "Use should use this if you have local modifications to these files that you want to keep.")

    args = CIME.utils.parse_args_and_handle_standard_logging_options(args, parser)

    return args.caseroot, args.clean, args.test_mode, args.reset, args.keep

###############################################################################
def _main_func(description):
###############################################################################
    caseroot, clean, test_mode, reset, keep = parse_command_line(sys.argv, description)
    with Case(caseroot, read_only=False) as case:
        case.case_setup(clean=clean, test_mode=test_mode, reset=reset, keep=keep)

if __name__ == "__main__":
    _main_func(__doc__)
